<?php
/**
 * InvitationCode Plugin
 * 邀请码注册
 *
 */
class InvitationCode_Action extends Typecho_Widget implements Widget_Interface_Do
{
    /** @var  数据操作对象 */
    private $_db;

    /** @var  插件配置信息 */
    private $_cfg;
    
    /** @var  系统配置信息 */
    private $_options;

    /**
     * 初始化
     * @return $this
     */
    public function init()
    {
        $this->_db = Typecho_Db::get();
        $this->_options = $this->widget('Widget_Options');
        $this->_cfg = Helper::options()->plugin('InvitationCode');
    }

    /**
     * action 入口
     *
     * @access public
     * @return void
     */
    public function action()
    {
        $this->on($this->request->is('do=generateCode'))->generateCode();
    }

    /**
     * 邀请码生成
     */
    public function generateCode()
    {
        if (Typecho_Widget::widget('InvitationCode_Console')->generateCodeForm()->validate()) {
            $this->response->goBack();
        }

        $this->init();
        $open_cxa = $this->_cfg->open_cxa;
        if($open_cxa == 'on'){
            $this->Create_database();
            $db_prefix = $this->_db->getPrefix();
            $form_data = $this->request->from('toNum_cxa');
            $prefix_cxa = $this->request->from('prefix_cxa');
            $prefix_cxa = $prefix_cxa['prefix_cxa'];
            $num_cxa = $this->request->from('num_cxa');
            $num_cxa = $num_cxa['num_cxa'];
            $duration_cxa = $this->request->from('duration_cxa');
            $duration_cxa = $duration_cxa['duration_cxa'];
            $duration = $duration_cxa == 0 ? 0 : time() + ($duration_cxa * 3600);
            for($i=1; $i <= $form_data['toNum_cxa']; $i++){
                $code = $prefix_cxa.date('yd').$this->randCode(12,0).date('s');
                $insert = $this->_db->insert("{$db_prefix}invitation_code")
                    ->rows(array('num' => $num_cxa, 'code' => $code,  'duration' => $duration));
                $insertId = $this->_db->query($insert);
            }
            $result = true;
            /** 提示信息 */
            $this->widget('Widget_Notice')->set(true === $result ? _t('邀请码生成成功') : _t('邀请码生成失败'),
                true === $result ? 'success' : 'notice');
        }else{
            /** 提示信息 */
            $this->widget('Widget_Notice')->set(_t('设置中未开启邀请码'),'notice');
        }
        /** 转向原页 */
        $this->response->goBack();
    }

    private function Create_database()
    {
        $db= Typecho_Db::get();
        $prefix = $db->getPrefix();
        $getAdapterName = $db->getAdapterName();
        $data_name=$prefix.'invitation_code';
        if(preg_match('/^M|m?ysql$/',$getAdapterName)){
            $query = $db->select('TABLE_NAME')->from("INFORMATION_SCHEMA.TABLES")->where("TABLE_NAME='{$data_name}'");
            $is_exist = $db->fetchRow($query);
            if($is_exist){
                return true;
            }
            $db->query("CREATE TABLE {$data_name} (
                          `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
                          `code` varchar(100) NOT NULL DEFAULT '',
                          `duration` int(10) unsigned NOT NULL DEFAULT '0',
                          `num` int(5) unsigned NOT NULL DEFAULT '1',
                          PRIMARY KEY (`id`),
                          KEY `code` (`code`)
                        ) ENGINE=MyISAM DEFAULT CHARSET=utf8");
        }elseif(preg_match('/^S|s?Q|q?L|l?ite$/',$getAdapterName)){
            $query = $db->select('name')->from("sqlite_master")->where("name={$data_name}");
            $is_exist = $db->fetchRow($query);
            if($is_exist){
                return true;
            }
            $db->query("CREATE TABLE {$data_name} ( 
                            \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                            \"code\" varchar(200) default NULL ,
                            \"duration\" int(10) default '0',
                            \"num\" int(5) default '1')");
            $db->query('CREATE INDEX invitation_code_code ON '.$data_name.' ("code")');
        }elseif(preg_match('/^P|p*?gsql$/is',$getAdapterName)){
            $query = $db->select('count(*)')->from("pg_class")->where(" relname = '{$data_name}'");
            $is_exist = $db->fetchRow($query);
            if($is_exist['count']){
                return true;
            }
            $db->query("CREATE TABLE \"{$data_name}\" (  
                              \"id\" INT8 NOT NULL DEFAULT nextval('invitation_code_seq'::regclass),
                              \"code\" VARCHAR(200) NULL DEFAULT NULL,
                              \"duration\" INT NULL DEFAULT '0',
                              \"num\" INT NULL DEFAULT '1',
                              PRIMARY KEY (\"id\"))");
            $db->query("CREATE INDEX \"invitation_code_code\" ON \"{$data_name}\" (\"code\")");
        }
    }

    private function randCode($length = 5, $type = 0) {
        $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
        if ($type == 0) {
            array_pop($arr);
            $string = implode("", $arr);
        } else if ($type == "-1") {
            $string = implode("", $arr);
        } else {
            $string = $arr[$type];
        }
        $count = strlen($string) - 1;
        $code='';
        for ($i = 0; $i < $length; $i++) {
            $str[$i] = $string[rand(0, $count)];
            $code .= $str[$i];
        }
        return $code;
    }
}